//
//  UIImagePickerController+Extension.swift
//  zhengwutong
//
//  Created by wangshuguan on 16/9/5.
//  Copyright © 2016年 wangshuguan. All rights reserved.
//

import UIKit
import Photos
import RSKImageCropper
class UIImagePickerControllerWraper:NSObject,UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    var block:((_ image:UIImage,_ editImage:UIImage?)->Void)?
    convenience init(b:@escaping ((_ image:UIImage,_ editImage:UIImage?)->Void)) {
        self.init()
        block = b
    }
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: {})
    }
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        picker.dismiss(animated: true, completion: {
            if (self.block != nil) {
                DispatchQueue.main.async {
                    let originalImage = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
                    let editedImage = info[UIImagePickerController.InfoKey.editedImage] as? UIImage
                    self.block!(originalImage.photoToNormal(),editedImage)
                }
            }
        })
    }

}
class EditImageControllerWraper:NSObject,RSKImageCropViewControllerDelegate {
    func imageCropViewControllerDidCancelCrop(_ controller: RSKImageCropViewController) {
        controller.dismiss(animated: true, completion: nil)
    }
    
    func imageCropViewController(_ controller: RSKImageCropViewController, didCropImage croppedImage: UIImage, usingCropRect cropRect: CGRect, rotationAngle: CGFloat) {
        controller.dismiss(animated: true) {[weak self] in
            if let SSelf = self{
                SSelf.block(croppedImage)
            }
        }
    }
    
    var block:((_ editImage:UIImage)->Void) = {_ in}
    convenience init(b:@escaping ((_ editImage:UIImage)->Void)) {
        self.init()
        block = b
    }

}
var k_UIImagePickerControllerExtensionKeyWraper = "k_UIImagePickerControllerExtensionKeyWraper"
extension UIImagePickerController {
    class func check(type:UIImagePickerController.SourceType,_ block:@escaping()->Void) {
        if type == .photoLibrary {
        
        switch PHPhotoLibrary.authorizationStatus() {
        case .authorized:
                DispatchQueue.main.async {
                    block()
                }
            break
        case .notDetermined:
            PHPhotoLibrary.requestAuthorization { (status) in
                    DispatchQueue.main.async {
                if status == .authorized{
                            block()
                }else{
                            UIAlertController.alertMessage("请在iPhone的\"设置-隐私-照片\"选项中，允许\(Config.App.displayName)访问你的手机相册")
                        }
                }
            }
            break
        default:
                UIAlertController.alertMessage("请在iPhone的\"设置-隐私-照片\"选项中，允许\(Config.App.displayName)访问你的手机相册")
            }
        }else if type == .camera{
            switch AVCaptureDevice.authorizationStatus(for: .video) {
                case .authorized: // The user has previously granted access to the camera.
                DispatchQueue.main.async {
                    block()
                }
                break
                
                case .notDetermined: // The user has not yet been asked for camera access.
                    AVCaptureDevice.requestAccess(for: .video) { granted in
                        DispatchQueue.main.async {
                            if granted {
                                block()
                            }else{
                                UIAlertController.alertMessage("请在iPhone的\"设置-隐私-相机\"选项中，允许\(Config.App.displayName)访问你的手机相机")
                            }
                        }
                    }
                    break
                
                case .denied: // The user has previously denied access.
                UIAlertController.alertMessage("请在iPhone的\"设置-隐私-相机\"选项中，允许\(Config.App.displayName)访问你的手机相机")
                break

                case .restricted: // The user can't grant access due to restrictions.
                UIAlertController.alertMessage("请在iPhone的\"设置-隐私-相机\"选项中，允许\(Config.App.displayName)访问你的手机相机")
                break
            @unknown default:
                UIAlertController.alertMessage("请在iPhone的\"设置-隐私-相机\"选项中，允许\(Config.App.displayName)访问你的手机相机")
                break
            }
        }else if type == .savedPhotosAlbum{

        }
    }
    func addSelectedBlock(_ block:@escaping (_ image:UIImage,_ editImage:UIImage?)->Void) -> Void {
        
        func dofunc(){
            objc_setAssociatedObject(self, &k_UIImagePickerControllerExtensionKeyWraper,UIImagePickerControllerWraper(b: block) , .OBJC_ASSOCIATION_RETAIN)
            self.delegate = objc_getAssociatedObject(self, &k_UIImagePickerControllerExtensionKeyWraper) as! UIImagePickerControllerWraper
        }
        dofunc()
    }
}
var k_EditImageControllerExtensionKeyWraper = "k_EditImageControllerExtensionKeyWraper"
extension RSKImageCropViewController{
    func addEditBlock(_ block:@escaping (_ editImage:UIImage)->Void) -> Void {
        func dofunc(){
            objc_setAssociatedObject(self, &k_EditImageControllerExtensionKeyWraper,EditImageControllerWraper(b: block) , .OBJC_ASSOCIATION_RETAIN)
            self.delegate = objc_getAssociatedObject(self, &k_EditImageControllerExtensionKeyWraper) as! EditImageControllerWraper
        }
        dofunc()
    }
}
class ETImageEditViewController: UIViewController,UIScrollViewDelegate {
    let scrollView = UIScrollView()
    let imageView = UIImageView()
    var image:UIImage = UIImage()
    let maskView = UIView()
    let controlButton = UIButton(type: .system)
    let maskLayer = CAShapeLayer()
    let saveButton = UIButton(type: .contactAdd)
    var realRadius:CGFloat = 0
    var saveAction:(UIImage)->Void = {_ in}
    let xuxianLayer = CAShapeLayer()
    override func viewDidLoad() {
        super.viewDidLoad()
        changeTopConstraint()
        self.view.addSubview(scrollView)
        scrollView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        scrollView.delegate = self
        scrollView.maximumZoomScale = 5
        scrollView.minimumZoomScale = 1
        
        imageView.image = image
        imageView.contentMode = .scaleAspectFit
        scrollView.addSubview(imageView)
        imageView.snp.makeConstraints { (make) in
            make.center.equalToSuperview()
            make.edges.equalToSuperview()
        }
        
        self.view.addSubview(maskView)
        maskView.isUserInteractionEnabled = false
        maskView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        maskView.backgroundColor = UIColor(white: 0, alpha: 0.5)
        
        
        controlButton.setTitle("控制", for: .normal)
        controlButton.sizeToFit()
        self.view.addSubview(controlButton)
        
        controlButton.isSelected = true
        let ge = UIPanGestureRecognizer(target: self, action: #selector(changeGe(_:)))
        controlButton.addGestureRecognizer(ge)
        
        maskLayer.fillRule = .evenOdd
        maskView.layer.mask = maskLayer
        maskView.layer.addSublayer(xuxianLayer)
        
        xuxianLayer.fillColor = UIColor.clear.cgColor
        xuxianLayer.strokeColor = UIColor.red.cgColor
        
        xuxianLayer.lineWidth = 5
        xuxianLayer.lineJoin = .round
        xuxianLayer.lineDashPhase = 0
        xuxianLayer.lineDashPattern = [NSNumber(value: 10), NSNumber(value: 20)]
        
        saveButton.addTarget(self, action: #selector(save)
            , for: .touchUpInside)
        self.view.addSubview(saveButton)
        saveButton.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-50)
            make.bottom.equalToSuperview().offset(-50)
        }
    }
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        let radio1 = image.size.width/image.size.height
        let radio2 = self.view.frame.size.width/self.view.frame.size.height
        var f_image = self.view.frame
        if radio1 > radio2{
            let w_image = self.view.frame.size.width
            let h_image = self.view.frame.size.width / radio1
            f_image = CGRect(x: 0, y: (self.view.frame.size.height-h_image)/2, width: w_image, height: h_image)
        }else{
            let h_image = self.view.frame.size.height
            let w_image = self.view.frame.size.height / radio1
            f_image = CGRect(x: (self.view.frame.size.width-w_image)/2, y: 0, width: w_image, height: h_image)
        }
        let radus = min(f_image.size.width,f_image.size.height)/2.0
        updateLayerFrame(CGPoint(x: cos(CGFloat.pi/4) * radus + self.view.frame.size.width/2.0, y: sin(CGFloat.pi/4) * radus + self.view.frame.size.height/2.0),controlButton)
    }
    func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        return imageView
    }
    func maskImage() -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(self.view.frame.size, false, UIScreen.main.scale)
        if let context = UIGraphicsGetCurrentContext(){
            context.setFillColor(red: 0, green: 0, blue: 0, alpha: 0.5)
            context.fill(CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height))
        }
        guard let img = UIGraphicsGetImageFromCurrentImageContext() else {
            UIGraphicsEndImageContext(); return nil }
        UIGraphicsEndImageContext()
        return img
    }
    @objc func save(){
        UIGraphicsBeginImageContextWithOptions(self.view.frame.size, false, UIScreen.main.scale)
        if let context = UIGraphicsGetCurrentContext(){
            let offsetY = self.view.frame.size.height/2.0 - self.realRadius
            let offsetX = self.view.frame.size.width/2.0 - self.realRadius
            let inPath = UIBezierPath(ovalIn: CGRect(x: offsetX, y: offsetY, width: self.realRadius*2, height: self.realRadius*2))
            inPath.addClip()
            scrollView.layer.render(in: context)
        }
        guard let img = UIGraphicsGetImageFromCurrentImageContext() else {
            UIGraphicsEndImageContext();return }
        UIGraphicsEndImageContext()
        saveAction(img)
    }
    @objc func changeGe(_ ge:UIGestureRecognizer){
        if ge.state == .changed{
            if let bt = ge.view{
                updateLayerFrame(ge.location(in: self.view), bt)
            }
        }
    }
    func updateLayerFrame(_ location:CGPoint, _ bt:UIView) {
        let radius:CGFloat = sqrt(pow((location.x - self.view.frame.size.width/2), 2) + pow((location.y - self.view.frame.size.height/2), 2))
        guard radius <= self.view.frame.size.width/2.0 else {
            return
        }
        bt.center = location
        let offsetY = self.view.frame.size.height/2.0 - radius
        let offsetX = self.view.frame.size.width/2.0 - radius
        let path = UIBezierPath(rect: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height))
        let inPath = UIBezierPath(ovalIn: CGRect(x: offsetX, y: offsetY, width: radius*2, height: radius*2))
        path.append(inPath)
        let realPath = path.cgPath
        maskLayer.path = realPath
        xuxianLayer.path = UIBezierPath(roundedRect: CGRect(x: offsetX, y: offsetY, width: radius*2, height: radius*2), cornerRadius: radius).cgPath
        realRadius = radius
    }
}

class UIDocumentPickerViewControllerWraper: NSObject,UIDocumentPickerDelegate {
    var block:((_ url:URL?)->Void)?
    convenience init(b:@escaping ((_ url:URL?)->Void)) {
        self.init()
        block = b
    }
    
    //MARK: - UIDocumentPickerDelegate
    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL){
        if (self.block != nil) {
            DispatchQueue.main.async {
                self.block!(url)
            }
        }
    }
}
var k_UIDocumentPickerViewControllerExtensionKeyWraper = "k_UIDocumentPickerViewControllerExtensionKeyWraper"
extension UIDocumentPickerViewController{
    func addSelectedBlock(_ block:@escaping (_ url:URL?)->Void) -> Void {
        
        func dofunc(){
            objc_setAssociatedObject(self, &k_UIDocumentPickerViewControllerExtensionKeyWraper,UIDocumentPickerViewControllerWraper(b: block) , .OBJC_ASSOCIATION_RETAIN)
            self.delegate = objc_getAssociatedObject(self, &k_UIDocumentPickerViewControllerExtensionKeyWraper) as! UIDocumentPickerViewControllerWraper
        }
        dofunc()
    }
}
